package com.bountytask.service.impl;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.bountytask.dao.UserDao;
import com.bountytask.entity.UserInfo;
import com.bountytask.service.LoginService;
import com.bountytask.util.RestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserDao userDao;

    @Value("${wx.access_token_url}")
    private String accessTokenUrl;

    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.secret}")
    private String secret;

    //jsonObject 就是利用code 获取到的json对象
    public String loginDecrypt(String encryptedData, JSONObject jsonObject, String vi) throws Exception {
        // 开始解密
        String sessionKey = (String) jsonObject.get("session_key");
        byte[] encData = cn.hutool.core.codec.Base64.decode(encryptedData);
        byte[] iv = cn.hutool.core.codec.Base64.decode(vi);
        byte[] key = Base64.decode(sessionKey);
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        return new String(cipher.doFinal(encData), "UTF-8");
    }

    /**
     * 判断用户是否已经注册过
     */
    public UserInfo getUserByOpenId(String openid){
        return userDao.getUserByOpenId(openid);
    }

    /**
     * 添加新用户
     */
    public JSONObject register(UserInfo user){
        JSONObject resultJson=new JSONObject(true);
        user.setSettleNum(0);
        user.setFinishNum(0);
        user.setGetNum(0);
        user.setPostNum(0);
        if(userDao.addUser(user)!=1){
            resultJson.put("code",400);
            resultJson.put("message","失败");
            return resultJson;
        }
        resultJson.put("code",200);
        resultJson.put("message","成功");
        return resultJson;
    }

    /**
     * 获取access_token
     */
    public String getWxAccessTokenUrl(){
        try {
            String url = accessTokenUrl.replace("APPID",appId).replace("APPSECRET",secret);
            log.info("请求获取access_token的url:" + url);
            return RestTemplateUtil.get(url);
        }catch (Exception e){
            e.printStackTrace();
            return "请求获取access_token出现异常";
        }
    }
}
